﻿using Microsoft.Build.Framework;
using Microsoft.Build.Evaluation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Microsoft.Build.Logging;

namespace Sasa.QualityTools.CodeAnalysis.MSBuild.Tests.Unit.Instruments
{
    public class MSBuildTaskRunner
    {
        public MSBuildResult Run(string taskName, string taskParameter)
        {
            var result = new MSBuildResult();

            var projects = new ProjectCollection();
            using (var reader = XmlReader.Create(new StringReader(String.Format(
                "<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>" +
                "    <UsingTask AssemblyFile='FxCopIntegrator.MSBuild.Tasks.dll' TaskName='{0}'/>" +
                "    <Target Name='target'>" +
                "        <{0} {1}/>" +
                "    </Target>" +
                "</Project>",
                taskName, taskParameter))))
            {
                var project = projects.LoadProject(reader);
                var logger = new ConsoleLogger(LoggerVerbosity.Normal, o => result.Outputs.Add(o), null, null);
                result.Success = project.Build("target", new List<ILogger> { logger });
            }

            projects.UnloadAllProjects();

            return result;
        }
    }
}
